{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\users\\顾哲\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:17: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working\n",
      "  from collections import Mapping, defaultdict\n"
     ]
    }
   ],
   "source": [
    "from sklearn.datasets import fetch_mldata\n",
    "mnist = fetch_mldata('mnist-original', data_home='./')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = mnist['data']\n",
    "y = mnist['target']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "shuffle_index = np.random.permutation(70000)\n",
    "X = X[shuffle_index]\n",
    "y = y[shuffle_index]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(60000, 784)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "numpy.ndarray"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X_train,y_train,X_test,y_test=X[:60000,:],y[:60000],X[60000:,:],y[60000:]\n",
    "print(X_train.shape)\n",
    "type(X_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def image_offset(data_s, direct='u', offset=1):\n",
    "    data_s = data_s.reshape(len(data_s), int(np.sqrt(len(data_s[1]))), -1)\n",
    "    size = len(data_s)\n",
    "    data_offset = np.zeros((size, 784))\n",
    "    if direct == 'u':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][offset:,:], data_s[i][:offset,:], axis=0)\n",
    "            data_offset[i] = trans_data.reshape(1, -1)\n",
    "    elif direct == 'd':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][-offset:,:], data_s[i][:-offset,:], axis=0)\n",
    "            data_offset[i] = trans_data.reshape(1, -1)\n",
    "    elif direct == 'l':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][:,offset:], data_s[i][:,:offset], axis=1)\n",
    "            data_offset[i] = trans_data.reshape(1, -1)\n",
    "    elif direct == 'r':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][:,-offset:], data_s[i][:,:-offset], axis=1)\n",
    "            data_offset[i] = trans_data.reshape(1, -1)\n",
    "    return data_offset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 2]\n",
      " [3 4 5]\n",
      " [6 7 8]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 0],\n",
       "       [4, 5, 3],\n",
       "       [7, 8, 6]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = np.arange(9)\n",
    "a = a.reshape(3,-1)\n",
    "print(a)\n",
    "b = np.append(a[1:,:], a[:1,:]).reshape(3,-1)\n",
    "b\n",
    "c = np.append(a[:,1:], a[:,:1], axis=1).reshape(3,-1)\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "X_train_u=image_offset(X_train,'u')\n",
    "X_train_d=image_offset(X_train,'d')\n",
    "X_train_l=image_offset(X_train,'l')\n",
    "X_train_r=image_offset(X_train,'r')\n",
    "\n",
    "print(type(X_train_u))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(60000, 784)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X_train_u.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train_new=np.concatenate((X_train,X_train_u,X_train_d,X_train_l,X_train_r),axis=0)\n",
    "y_train_new=np.concatenate((y_train,y_train,y_train,y_train,y_train),axis=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.metrics import precision_score, recall_score\n",
    "from sklearn.model_selection import cross_val_score, cross_val_predict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n",
       "           metric_params=None, n_jobs=1, n_neighbors=5, p=2,\n",
       "           weights='uniform')"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "kn_clf=KNeighborsClassifier()\n",
    "kn_clf.fit(X_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_test_pred=cross_val_predict(kn_clf,X_test,y_test,cv=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "precision = precision_score(y_test, y_test_pred, average='macro')\n",
    "recall = recall_score(y_test, y_test_pred, average='macro')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9331435638114242\n",
      "0.9290157050934852\n"
     ]
    }
   ],
   "source": [
    "print(precision)\n",
    "print(recall)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
